package ifly

import (
	"bytes"
	"fmt"
	"github.com/spf13/viper"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"
)

func New(slugs ...string) *Ifly {
	slug := "default"
	if len(slugs) > 0 {
		slug = slugs[0]
	}

	apiKey := viper.GetString(fmt.Sprintf("org.ifly.auth.%s.apiKey", slug))
	apiSecret := viper.GetString(fmt.Sprintf("org.ifly.auth.%s.apiSecret", slug))
	proxy := viper.GetString(fmt.Sprintf("org.ifly.auth.%s.proxy", slug))

	return &Ifly{
		apiKey:    apiKey,
		apiSecret: apiSecret,
		proxy:     proxy,
		protocol:  "HTTP/1.1",
	}
}

type Ifly struct {
	apiKey    string
	apiSecret string
	proxy     string
	protocol  string
}

func (r *Ifly) GetClient() *http.Client {
	transport := &http.Transport{}
	if r.proxy != "" {
		proxyUrl, err := url.Parse(r.proxy)
		if err != nil {
			panic(err)
		}

		transport.Proxy = http.ProxyURL(proxyUrl)
	}

	return &http.Client{
		Transport: transport,
	}
}
func (r *Ifly) DoRequest(method, protocol, endpoint, uri string, tt []byte) string {
	request, err := http.NewRequest(method, fmt.Sprintf("%s://%s%s", protocol, endpoint, uri), bytes.NewReader(tt))
	if err != nil {
		panic(err)
	}

	currentTime := time.Now().UTC().Format(time.RFC1123)
	digest := "SHA-256=" + signBody(tt)
	sign := generateSignature(endpoint, currentTime, "POST", uri, r.protocol, digest, r.apiSecret)
	authHeader := fmt.Sprintf(`api_key="%s", algorithm="%s", headers="host date request-line digest", signature="%s"`, r.apiKey, "hmac-sha256", sign)

	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("Accept", "application/json,version=1.0")
	request.Header.Set("Host", endpoint)
	request.Header.Set("Date", currentTime)
	request.Header.Set("Digest", digest)
	request.Header.Set("Authorization", authHeader)

	response, err := r.GetClient().Do(request)
	if err != nil {
		panic(err)
	}

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		panic(err)
	}
	response.Body.Close()

	return string(body)
}
